package com.sf.su.marathon.web.controller;

import com.alibaba.fastjson.JSON;
import com.sf.su.marathon.Const.Const;
import com.sf.su.marathon.dao.domain.User;
import com.sf.su.marathon.dao.dto.FakeUser;
import com.sf.su.marathon.model.OpenidResult;
import com.sf.su.marathon.service.UserService;
import com.sf.su.marathon.utils.HttpClientUtils;
import com.sf.su.marathon.utils.Result;
import com.sf.su.marathon.utils.UUIDUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author 591030 on 2017/12/14.
 */
@RequestMapping("user")
@Controller
public class UserController {

    private String appId="wx294fed182eed8ecc";

    private String appSecret="8611dd8ab4f651ea3a0802a798119067";

    private String openIdUrl="https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private UserService userService;

    @RequestMapping(value = "getResourceId",method = RequestMethod.POST)
    @ResponseBody
    public Result getResourceId(String jsCode, String userInfo) {
        FakeUser fakeUser = JSON.parseObject(userInfo,FakeUser.class);
        User user = new User();
        user.setName(fakeUser.getNickName());
        user.setHeadImg(fakeUser.getAvatarUrl());
        String url = openIdUrl + "?appid=" + appId + "&secret=" + appSecret
                + "&js_code=" + jsCode + "&grant_type=authorization_code";
        OpenidResult openidResult = JSON.parseObject(HttpClientUtils.sendGet(url), OpenidResult.class);
        if (openidResult != null) {
            String openid = openidResult.getOpenid();
            user.setOpenId(openid);
            String resourceId =openid;
            if(userService.getUserByResourceId(resourceId)!=null){
                return Result.buildResp(Const.FAILSTATUS,"已经登陆",resourceId);

            }
            if (!StringUtils.isEmpty(openidResult.getErrcode())) {
                return Result.buildResp(Const.FAILSTATUS,"get open id with error",openidResult.getErrmsg());
            }
            user.setId(UUIDUtils.getUUID());

            if(userService.insert(user)>0){
                return Result.buildResp(Const.SUCCESSSTATUS,user.getId(),resourceId);
            }
        }
        return Result.buildResp(Const.FAILSTATUS,"requesting wechat can not get value",null);
    }

}
